import { useState, useEffect } from 'react'

import {
  Card,
  Table,
  Button,
  Input,
  Space,
  Badge,
  Popconfirm,
  Message,
  Typography,
  Tag,
} from '@arco-design/web-react'
import {
  IconPlus,
  IconSearch,
  IconEdit,
  IconDelete,
  IconPlayArrow,
  IconHistory,
} from '@arco-design/web-react/icon'
import { getPipelines, deletePipeline, executePipeline } from '@/api/pipeline'
import type { Pipeline } from '@/types'
import PipelineFormModal from '@/components/PipelineFormModal'

import './index.css'

const { Title } = Typography

export default function PipelinePage() {

  const [loading, setLoading] = useState(false)
  const [pipelines, setPipelines] = useState<Pipeline[]>([])
  const [searchText, setSearchText] = useState('')
  const [executing, setExecuting] = useState<Record<number, boolean>>({})
  const [formVisible, setFormVisible] = useState(false)
  const [editingPipeline, setEditingPipeline] = useState<Pipeline | null>(null)

  // 加载流水线列表
  const loadPipelines = async () => {
    setLoading(true)
    try {
      const data = await getPipelines()
      setPipelines(data)
    } catch (error) {
      console.error('Failed to load pipelines:', error)
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    loadPipelines()
  }, [])

  // 执行流水线
  const handleExecute = async (id: number) => {
    setExecuting((prev) => ({ ...prev, [id]: true }))
    try {
      await executePipeline(id)
      Message.success('流水线已开始执行')
    } catch (error) {
      console.error('Failed to execute pipeline:', error)
    } finally {
      setExecuting((prev) => ({ ...prev, [id]: false }))
    }
  }

  // 删除流水线
  const handleDelete = async (id: number) => {
    try {
      await deletePipeline(id)
      Message.success('删除成功')
      loadPipelines()
    } catch (error) {
      console.error('Failed to delete pipeline:', error)
    }
  }

  // 过滤数据
  const filteredData = pipelines.filter((item) =>
    item.name.toLowerCase().includes(searchText.toLowerCase())
  )

  const columns = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      render: (name: string) => <strong>{name}</strong>,
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '工作流',
      dataIndex: 'workflowDefinition.name',
      key: 'workflowName',
      render: (name: string) => <Tag color="arcoblue">{name || '-'}</Tag>,
    },
    {
      title: '仓库',
      dataIndex: 'repositoryUrl',
      key: 'repositoryUrl',
      render: (url: string) => (
        <Typography.Text
          ellipsis={{ showTooltip: true }}
          style={{ maxWidth: 300 }}
        >
          {url}
        </Typography.Text>
      ),
    },
    {
      title: '分支',
      dataIndex: 'branch',
      key: 'branch',
      width: 120,
      render: (branch: string) => <Tag>{branch}</Tag>,
    },
    {
      title: '状态',
      dataIndex: 'isEnabled',
      key: 'isEnabled',
      width: 100,
      render: (isEnabled: boolean) => (
        <Badge status={isEnabled ? 'success' : 'default'} text={isEnabled ? '启用' : '禁用'} />
      ),
    },
    {
      title: '操作',
      key: 'action',
      width: 280,
      render: (_: any, record: Pipeline) => (
        <Space>
          <Button
            type="primary"
            size="small"
            icon={<IconPlayArrow />}
            loading={executing[record.id]}
            onClick={() => handleExecute(record.id)}
            disabled={!record.isEnabled}
          >
            执行
          </Button>
          <Button
            type="text"
            size="small"
            icon={<IconHistory />}
            onClick={() => window.location.href = `/pipeline/${record.id}/history`}
          >
            历史
          </Button>
          <Button
            type="text"
            size="small"
            icon={<IconEdit />}
            onClick={() => {
              setEditingPipeline(record)
              setFormVisible(true)
            }}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除此流水线吗？"
            onOk={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="text" size="small" status="danger" icon={<IconDelete />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ]

  return (
    <div className="pipeline-page">
      <Title heading={4} style={{ marginBottom: 20 }}>
        流水线管理
      </Title>

      <Card>
        <div className="pipeline-toolbar">
          <Space>
            <Button
              type="primary"
              icon={<IconPlus />}
              onClick={() => {
                setEditingPipeline(null)
                setFormVisible(true)
              }}
            >
              创建流水线
            </Button>
          </Space>

          <Input
            style={{ width: 300 }}
            placeholder="搜索流水线名称"
            prefix={<IconSearch />}
            value={searchText}
            onChange={setSearchText}
            allowClear
          />
        </div>

        <Table
          columns={columns}
          data={filteredData}
          loading={loading}
          pagination={{
            pageSize: 10,
            showTotal: true,
            showJumper: true,
            sizeCanChange: true,
          }}
          rowKey="id"
          style={{ marginTop: 16 }}
        />
      </Card>

      <PipelineFormModal
        visible={formVisible}
        pipeline={editingPipeline}
        onCancel={() => {
          setFormVisible(false)
          setEditingPipeline(null)
        }}
        onSuccess={() => {
          setFormVisible(false)
          setEditingPipeline(null)
          loadPipelines()
        }}
      />
    </div>
  )
}
